package com.ermax.aircond.maintain.web.bean;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

import org.springframework.context.annotation.Scope;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import com.ermax.aircond.common.domain.UserDetail;
import com.ermax.aircond.common.domain.UserGroup;
import com.ermax.aircond.common.service.UserFilterService;
import com.ermax.aircond.maintain.service.MaintainService;
import com.ermax.aircond.resource.MessageBundle;
import com.ermax.aircond.util.web.bean.DataTableBean;

@Scope("view")
@Component
public class UserMaintainBean extends DataTableBean implements java.io.Serializable{

	private static final long serialVersionUID = 1L;
	private static final String ROLE_ADMIN = "ROLE_ADMIN";
	
	@Resource(name="maintainService")
	private MaintainService maintainService;		
	
	@Resource(name="userFilterService")
	private UserFilterService userFilterService;	
	
	private UserDetail editedItem  = new UserDetail();;
	private List<UserDetail> userDetails = new ArrayList<UserDetail>();
	private List<SelectItem> userGroupOptions = new ArrayList<SelectItem>();
	private List<String> selectedUserGroupIds = new ArrayList<String>();
	
	
	@PostConstruct
	public void init() {
		try{						
			reset();
		}catch(Exception ex){
			String message = MessageBundle.getInstance().getMessage("error_init_fail", FacesContext.getCurrentInstance().getViewRoot().getLocale()); 
			FacesMessage facesMessage  = new FacesMessage(message);
			FacesContext.getCurrentInstance().addMessage(null,facesMessage);
		}
	}
	
	private boolean checkAdmin() {
		boolean adminCheck = false;
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();		
		for (GrantedAuthority authority : authentication.getAuthorities()) {
			if(authority.getAuthority().equals(ROLE_ADMIN)) {
				adminCheck = true;
			}	
		}
		return adminCheck;
	}
	
	private void reset() throws Exception {
		
		if (checkAdmin()) {
			userDetails = maintainService.getAllUserDetails();
		} else {
			//userDetails = maintainService.getAllUserDetails();
			//userDetails = userFilterService.filterAdminUserDetails(userDetails);
			userDetails = maintainService.findUserDetailsNotInGroup(ROLE_ADMIN,null);
		}
		 
		userGroupOptions = createUserGroupOptions();	
	}
	
	public List<SelectItem> createUserGroupOptions() throws Exception{
		List<SelectItem> results = new ArrayList<SelectItem>();
		//List<UserGroup> userGroups =  maintainService.getAllUserGroups();
		
		List<UserGroup> userGroups = null;
		if (checkAdmin()) {
			userGroups = maintainService.getAllUserGroups();
		} else {
			userGroups = maintainService.getUserGroupsNotIn(ROLE_ADMIN);
		}
		
		for(UserGroup userGroup : userGroups){
			results.add(new SelectItem(userGroup.getUserGroupId(), userGroup.getGroupName()));
		}
		return results;
	}
	
	public void valueChangeUserGroupIds(){
		selectedUserGroupIds.clear();
		if(editedItem != null){			
			List<UserGroup> userGroups = editedItem.getUserGroups();
			for(UserGroup userGroup : userGroups){				
				selectedUserGroupIds.add(String.valueOf(userGroup.getUserGroupId()));
			}
		}
	}
	
	public void create(){
		try{	
			UserDetails userDetails=  (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			List<UserGroup> selectedUserGroups = new ArrayList<UserGroup>();
			for(String userGroupIdStr : selectedUserGroupIds){
				long id = Long.parseLong(userGroupIdStr);
				UserGroup userGroup = maintainService.getUserGroupById(id);
				selectedUserGroups.add(userGroup);
			}
			editedItem.setUserGroups(selectedUserGroups);
			
			maintainService.createUserDetail(editedItem, userDetails.getUsername());
			userFilterService.reset();
			
			reset();
		}catch(Exception ex){
			String message = MessageBundle.getInstance().getMessage("error_create_fail", FacesContext.getCurrentInstance().getViewRoot().getLocale()); 
			FacesMessage facesMessage  = new FacesMessage(message);
			FacesContext.getCurrentInstance().addMessage(null,facesMessage);
		}
	}
	
	public void remove(){
		try{		
			UserDetail userDetail = userDetails.get(getCurrentIndex());
			maintainService.deleteUserDetail(userDetail);
			userFilterService.reset();
			
			reset();
		}catch(Exception ex){
			String message = MessageBundle.getInstance().getMessage("error_remove_fail", FacesContext.getCurrentInstance().getViewRoot().getLocale()); 
			FacesMessage facesMessage  = new FacesMessage(message);
			FacesContext.getCurrentInstance().addMessage(null,facesMessage);
		}
	}
	
	public void update(){
		try{
			UserDetails userDetails=  (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			
			List<UserGroup> selectedUserGroups = new ArrayList<UserGroup>();
			for(String userGroupIdStr : selectedUserGroupIds){
				long id = Long.parseLong(userGroupIdStr);
				UserGroup userGroup = maintainService.getUserGroupById(id);
				selectedUserGroups.add(userGroup);
			}
			editedItem.setUserGroups(selectedUserGroups);
			maintainService.updateUserDetail(editedItem, userDetails.getUsername());
			userFilterService.reset();
			
			reset();
		}catch(Exception ex){
			String message = MessageBundle.getInstance().getMessage("error_update_fail", FacesContext.getCurrentInstance().getViewRoot().getLocale()); 
			FacesMessage facesMessage  = new FacesMessage(message);
			FacesContext.getCurrentInstance().addMessage(null,facesMessage);
		}
	}
	
	public void search() {
		try{
			
			if (checkAdmin()) {
				userDetails = maintainService.getUserDetails(getSearchStr());
			} else {
				//userDetails = maintainService.getUserDetails(getSearchStr());
				//userDetails = userFilterService.filterAdminUserDetails(userDetails);

				userDetails.clear();
				userDetails = maintainService.findUserDetailsNotInGroup(ROLE_ADMIN, getSearchStr());
			}			
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}	
	
	public void newItem(){
		editedItem = new UserDetail();
	}

	
	public List<UserDetail> getUserDetails() {
		return userDetails;
	}
	
	public void setUserDetails(List<UserDetail> userDetails) {
		this.userDetails = userDetails;
	}

	public UserDetail getEditedItem() {
		return editedItem;
	}

	public void setEditedItem(UserDetail editedItem) {
		this.editedItem = editedItem;
	}

	public List<SelectItem> getUserGroupOptions() {
		return userGroupOptions;
	}

	public void setUserGroupOptions(List<SelectItem> userGroupOptions) {
		this.userGroupOptions = userGroupOptions;
	}

	public List<String> getSelectedUserGroupIds() {
		return selectedUserGroupIds;
	}

	public void setSelectedUserGroupIds(List<String> selectedUserGroupIds) {
		this.selectedUserGroupIds = selectedUserGroupIds;
	}
	

	
}
